
import $fetch from '@system.fetch'
import storage from '@system.storage'
import prompt from '@system.prompt'
import { refreshToken } from './login/index'
import router from '@system.router'
import visitorLogin from './login/visitor-login'
const TIMEOUT = 20000
let requestQueue = []
let isTokenRefreshing = false;
function clearRequestQueue(){
    requestQueue.forEach(callback => {
        callback()
    })
    requestQueue = []
}

Promise.prototype.finally = function (callback) {
    const P = this.constructor
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason =>
            P.resolve(callback()).then(() => {
                throw reason
            })
    )
}

/**
 * 调用快应用 fetch 接口做网络请求
 * @param params
 */
let header = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',

    // 'encrypt-key':decryptByRsa()
}

// const baseUrl = 'https://maimengadmin.test.youmanvideo.com/dev-app-api'
const baseUrl = 'https://maimengadmin.test.youmanvideo.com/dev-app-quick-api'
async function request({ url, data, method = 'POST', callback = null }) {
    const token = await storage.get({
        key:'token'
    })
    if (token?.data) {
        header.Authorization = `Bearer ${token.data}`
    }
    const options = {
        header,
        url: baseUrl + url,
        method: method,
        data: data,
        dataType: 'json',
    }
    return new Promise((resolve, reject) => {
        $fetch
            .fetch(options)
            .then(response => {
                const result = response.data
                const content = JSON.parse(result.data)
                console.log('接口状态吗:', content.code)
                /* @desc: 可跟具体不同业务接口数据，返回你所需要的部分，使得使用尽可能便捷 */
                if (content.code == '200') {
                    resolve(content.data)
                } else {
                    if (content.code == 401) {
                        let _options = JSON.parse(JSON.stringify(options))
                        _options.url = url
                        requestQueue.push(()=>request(_options))
                        if (!isTokenRefreshing) {
                            isTokenRefreshing = true
                            try{
                                refreshToken().then(res => {
                                    isTokenRefreshing = false
                                    clearRequestQueue()
                                }).catch(e=>{
                                    visitorLogin().then(()=>{
                                        const routes = router.getPages()
                                        console.log('router',routes)
                                        let r = null
                                        if(routes.length){
                                            r = routes.length && routes[0]
                                        }
                                        if(r.name == 'pages/recommend'){
                                            router.push({
                                                uri:`/pages/login?from=pages/recommend`
                                            })
                                        }else{
                                            router.push({
                                                uri:'/pages/login'
                                            })
                                        }
                                    })
                                })
                            }catch(e){
                                console.log('刷新token',e)
                            }
                        }
    
                    } else {                
                        reject(content)
                        prompt.showToast({
                            message: content.msg || '',
                        });
                    }
                    reject(content)
                }
            })
    })
}

/**
 * 处理网络请求，timeout 是网络请求超时之后返回，默认 20s 可自行修改
 * @param params
 */
function requestHandle(params, timeout = TIMEOUT) {
    try {
        return Promise.race([
            fetchPromise(params),
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject(new Error('网络状况不太好，再刷新一次？'))
                }, timeout)
            })
        ])
    } catch (error) {
        console.log(error)
    }
}

export {
    request
}